import numpy as np
import cv2 as cv
def detect_video(video):
    cap=cv.VideoCapture(video)
    fgbg=cv.createBackgroundSubtractorMOG2()

    # frames = 0
    while(1):
        ret,frame=cap.read()
        fgmask=fgbg.apply(frame)

        # if frames < history:
        #     frames += 1
        #     continue

        # 对原始帧进行膨胀去噪
        # th = cv.threshold(fgmask.copy(), 244, 255, cv.THRESH_BINARY)[1]
        # th = cv.erode(th, cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3)), iterations=2)
        # dilated = cv.dilate(th, cv.getStructuringElement(cv.MORPH_ELLIPSE, (8, 3)), iterations=2)
        # 获取所有检测框
        image, contours, hier = cv.findContours(fgmask, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
        for c in contours:
            # 获取矩形框边界坐标
            x, y, w, h = cv.boundingRect(c)
            area = cv.contourArea(c)
            if 500 < area < 2000:
               cv.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
               print("x=",x)
               print("y=",y)
               print("w=",w)
               print("h=",h)
        cv.imshow("detection", frame)
        cv.imshow("frame",fgmask)
        # cv.imshow("back", dilated)
        k=cv.waitKey(30)&0xff
        if k==27:
            break;
    cap.release()
    cv.destroyAllWindows()


if __name__ == '__main__':
    video = "G:\\Program Files\\opencv\\sources\\samples\\data\\vtest.avi"
    detect_video(video)